package com.soriya.nestlive.im

import android.util.Log
import com.google.gson.GsonBuilder
import com.soriya.nestlive.constant.ServerConstant
import com.soriya.nestlive.im.message.IMMessage
import com.soriya.nestlive.im.serializer.MessageTypeDeserializer
import com.soriya.nestlive.im.serializer.MessageTypeSerializer
import io.netty.bootstrap.Bootstrap
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelInitializer
import io.netty.channel.ChannelOption
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioSocketChannel
import io.netty.handler.codec.string.StringDecoder
import io.netty.handler.codec.string.StringEncoder
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class NettyClient @Inject constructor(
    private val imHandler: ImHandler
) {

    private val channelFuture: ChannelFuture by lazy {
        val eventExecutors = NioEventLoopGroup()
        Bootstrap().group(eventExecutors)
            .channel(NioSocketChannel::class.java)
            .option(ChannelOption.TCP_NODELAY, true)
            .handler(object : ChannelInitializer<SocketChannel>() {
                override fun initChannel(ch: SocketChannel?) {
                    ch?.pipeline()?.addLast("encoder", StringEncoder())
                    ch?.pipeline()?.addLast("decoder", StringDecoder())
                    ch?.pipeline()?.addLast(imHandler)
                }
            })
            .connect(ServerConstant.TCP_HOST, ServerConstant.TCP_PORT).addListener {
                if (it.isSuccess) {
                    Log.i("SoRiya", "TCP: 服务连接成功 By ${ServerConstant.TCP_HOST}:${ServerConstant.TCP_PORT}")
                }
            }
    }

    init {
        Log.i("SoRiya", "初始化Netty...")
        channelFuture
    }

    fun sendMessage(message: IMMessage) {
        val imMessage = GsonBuilder()
            .registerTypeAdapter(MessageType::class.java, MessageTypeSerializer())
            .registerTypeAdapter(MessageType::class.java, MessageTypeDeserializer())
            .create()
            .toJson(message)

        Log.i("SoRiya", "发送消息: $imMessage")

        channelFuture.channel().writeAndFlush(imMessage)
    }

}